﻿using System;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using netCoreStudy.Entities.Base;

namespace netCoreStudy.Extensions
{
	/// <summary>
	/// 验证服务 设置
	/// </summary>
	public static class ValidatorSetup
	{
		public static void AddValidatorSetup(this IServiceCollection services)
		{
			if (services == null) throw new ArgumentNullException(nameof(services));

			// override modelState // 替换 掉 原有的 modelState 验证改用 fluentValidation 
			services.Configure<ApiBehaviorOptions>(options =>
			{
				options.InvalidModelStateResponseFactory = (context) =>
				{
					var errors = context.ModelState.Values
						.Select(x => x.Errors
							.Select(p => p.ErrorMessage))
						.ToList();
					var result = errors.SelectMany(x => x);
					var res = string.Join("\n", result);

					return new OkObjectResult(new ResMsg(false,res, 400));
				};
			});
		}
	}
}